package com.ccg.plat.presentation.ui.feature2.viewmodel

import android.app.Activity
import android.app.Application
import android.widget.Toast
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import cn.jpush.android.api.JPushInterface
import com.ccg.plat.R
import com.ccg.plat.data.local.cache.UserInfoCache
import com.ccg.plat.presentation.common.base.viewmodel.BaseViewModelC
import com.ccg.plat.presentation.common.util.NavigationUtils
import com.ccg.plat.presentation.ui.feature2.model.NavigationItem
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.consumeAsFlow

/**
 * @author : C4_雍和
 * 描述 :
 * 主要功能 :
 * 维护人员 : C4_雍和
 * date : 2025/8/9 8:34
 */
class MainViewModel(application: Application) : BaseViewModelC(application) {
    /**
     * 定义意图
     */
    sealed class ContentIntent {
        /**
         * 跳转到房间列表页面
         * @property activity Activity
         * @constructor
         */
        class GoRoomListActivity(val activity: Activity) : ContentIntent()

        /**
         * 跳转到收藏夹
         * @property activity Activity
         * @constructor
         */
        class GoCollectActivity(val activity: Activity) : ContentIntent()
    }

    data class NaviViewState(var navigationItems: List<NavigationItem> = emptyList())

    val newsChannel = Channel<ContentIntent>(Channel.UNLIMITED)
    var uiState by mutableStateOf(NaviViewState())

    init {
        handleIntent()
    }

    private fun handleIntent() {
        launch(Dispatchers.IO) {
            newsChannel.consumeAsFlow().collect { data ->
                when (data) {
                    is ContentIntent.GoRoomListActivity -> {
                        NavigationUtils.goRoomListActivity(data.activity)
                    }

                    is ContentIntent.GoCollectActivity -> {
                        if (UserInfoCache.isVip()) {
                            NavigationUtils.goCollectActivity(data.activity)
                        } else {
                            launch(Dispatchers.Main) {
                                Toast.makeText(data.activity, "免费用户不能使用收藏夹", Toast.LENGTH_SHORT).show()
                            }
                        }
                    }
                }
            }
        }
    }

    fun initData() {
        uiState.navigationItems = listOf(NavigationItem(title = "首页", selectedId = R.mipmap.main_shouye_light), NavigationItem(title = "我的", selectedId = R.mipmap.main_personal_light))
        UserInfoCache.setJpushId(JPushInterface.getRegistrationID(getApplication()))
    }
}